package com.test28_类库应用;

import org.junit.Test;

/**
 * 描述数据的验证
 */
interface IValidator {
    /** 数据验证处理 */
    public boolean test();
}

/**
 * 邮箱验证
 */
class EmailValidator implements IValidator {
    public static final String DEFAULT_EMAIL_REGEX = "\\w+@\\w+\\.\\w+";    // 默认验证
    private String regex;   // 正则表达式
    private String content; // 要处理的内容

    public EmailValidator(String content) {
        this(content, DEFAULT_EMAIL_REGEX);
    }

    public EmailValidator(String content, String regex) {
        this.content = content;
        this.regex = regex;
    }

    @Override
    public boolean test() {
        if (this.content == null || "".equals(this.content)) {
            return false;
        }
        return this.content.matches(this.regex);
    }
}

class ValidatorFactory {
    private ValidatorFactory() {
    }

    public static IValidator getInstance(String content, String... regex) {
        if (regex.length == 0) {
            return new EmailValidator(content);
        } else {
            return new EmailValidator(content, regex[0]);
        }
    }
}

/**
 * Email验证
 */
public class YootkDemo_03 {

    @Test
    public void test1() {
        // 正则匹配email
        String str = "muyan.yootk-lixinghua@yootk.com";
        // 用户名：[a-zA-Z_][a-zA-Z0-9\-_\.]+
        // 固定字符：@
        // 域名：[a-zA-Z0-9\-]+
        // 结尾：\.(com|com\.cn|net|net\.cn|gov|edu)
        StringBuilder regex = new StringBuilder();
        regex.append("[a-zA-Z_][a-zA-Z0-9\\-_\\.]+");
        regex.append("@");
        regex.append("[a-zA-Z0-9\\-]+");
        regex.append("\\.(com|com\\.cn|net|net\\.cn|gov|edu)");
        System.out.println(str.matches(regex.toString()));
    }

    @Test
    public void test2() {
        {
            IValidator validator = ValidatorFactory.getInstance("muyan@yootk.com");
            System.out.println(validator.test() ? "当前的验证通过！" : "当前的Email数据输入错误！");
        }
        {
            // 传递特殊的Email验证规则
            IValidator validator = ValidatorFactory.getInstance("muyan@yootk.com.cn2",
                    "[a-zA-Z][a-zA-Z0-9_\\-\\.]+@\\w+\\.(com|com\\.cn|net|net\\.cn|gov|edu|org)");
            System.out.println(validator.test() ? "当前的验证通过！" : "当前的Email数据输入错误！");
        }
    }
}
